/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.network;

import Server.domain.ServerDomainController;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Ripper
 */
public class NetworkMainServer implements Runnable
{
    private ServerDomainController sdc;
    private List<Thread> runningThreads;
    private List<NetworkServer> threadContents;
    private ServerSocket serverSocket;
    private int PORT;
    
    private boolean running;
    
    
    public NetworkMainServer(ServerDomainController servDomCon, int prt) throws IOException
    {
        sdc = servDomCon;
        PORT = prt;
        
        runningThreads = new ArrayList<Thread>();
        threadContents = new ArrayList<NetworkServer>();
        serverSocket = new ServerSocket(PORT);
        
        running = true;
    }
    
    public void logMessageToScreen(String msg)
    {
        sdc.logMessageToScreen(msg);
    }
    
    @Override
    public void run()
    {
        logMessageToScreen("Launching main server.");
        
        Socket link = null;
        while(isRunning())
        {
            try
            {
                link = serverSocket.accept();
                
                launchNewThread(link);
                link = null;
            }
            catch(Exception ex)
            {
                
            }
            
            try
            {
                Thread.sleep(2);
                removeClosedThreads();
            }
            catch(Exception ex)
            {
                
            }
        }
        
        logMessageToScreen("Closing main server.");
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
    
    private void removeClosedThreads()
    {
        for(int a = 0; a < runningThreads.size(); a++)
        {
            if(!runningThreads.get(a).isAlive())
            {
                sdc.logout(threadContents.get(a).getActiveuser());
                
                runningThreads.remove(a);
                threadContents.remove(a);
            }
        }
    }
    public void launchNewThread(Socket link)
    {
        logMessageToScreen("New incoming connection: "+link.getInetAddress().getHostAddress());
        NetworkServer ns = new NetworkServer(sdc, link);
        threadContents.add(ns);
        
        Thread t = new Thread(ns);

        t.start();
        runningThreads.add(t);
    }

}
